package com.acwing.partition43;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2022/6/16 16:47
 */
public class AC4273链表合并 {

    private static final int N = 100010;
    private static int[] v = new int[N], ne = new int[N];
    private static List<int[]> a = new ArrayList<>(N), b = new ArrayList<>(N), c = new ArrayList<>(N);
    private static int h1, h2, n;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        h1 = nextInt(); h2 = nextInt(); n = nextInt();
        for (int i = 0; i < n; i++) {
            int addr = nextInt(), val = nextInt(), next = nextInt();
            v[addr] = val;
            ne[addr] = next;
        }
        for (int i = h1; i != -1; i = ne[i]) a.add(new int[]{i, v[i]});
        for (int i = h2; i != -1; i = ne[i]) b.add(new int[]{i, v[i]});
        if (a.size() < b.size()) {
            List<int[]> t = a;
            a = b;
            b = t;
        }
        for (int i = 0, j = b.size() - 1; i < a.size(); i += 2, j--) {
            c.add(a.get(i));
            if (i + 1 < a.size()) c.add(a.get(i + 1));
            if (j >= 0) c.add(b.get(j));
        }
        for (int i = 0; i < c.size(); i++) {
            writer.format("%05d %d ", c.get(i)[0], c.get(i)[1]);
            if (i + 1 < c.size()) writer.format("%05d\n", c.get(i + 1)[0]);
            else writer.println("-1");
        }
        writer.flush();
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
